//
//  MBLottieView.swift
//  PassionPulse
//
//  Created by kyo on 2024/2/5.
//

import UIKit
import Lottie
@objcMembers class MBLottieView: UIView {
    func show(name: String,loop: Bool,finishState: Bool, completionBlock: LottieCompletionBlock? = nil) -> Void {
        for view in subviews {
            if view.isKind(of: LottieAnimationView.self) {
                view.removeFromSuperview()
            }
        }
        let lota = LottieAnimationView.init(frame: self.bounds)
        lota.loopMode = .playOnce
        if loop {
            lota.loopMode = .loop
        }
        
        if name == "launchVideo.json" {
            //启动动画特殊填充
            lota.contentMode = .scaleAspectFill
        } else {
            lota.contentMode = .scaleAspectFit
        }
        
        if finishState {
            lota.backgroundBehavior = .forceFinish
        } else {
            lota.backgroundBehavior = .continuePlaying
        }
        self.addSubview(lota)
        
        let  animation = LottieAnimation.named(name,animationCache: DefaultAnimationCache.sharedCache)

        lota.animation = animation
        lota.play { completed in
            if Thread.isMainThread {
                completionBlock!(completed)
            } else {
                DispatchQueue.main.async {
                    completionBlock!(completed)
                }
            }
            if finishState {
                self.removeFromSuperview()
            }
        }
    }
}
